<?php 

header("Content-Type: application/json");
set_time_limit(0);

switch ($_POST['type']) {
    case '1':
        getAI('/thirdApi/bss/findCallDetailById',$_POST['data']);  //获取AI客服通话详情
        break;
    case '2':
        setJsonTell('json/yidu.json',$_POST['data']);
        break;
    case '3':
        createRenWu_tell($_POST['planId'],$_POST['starTime'],$_POST['endTime']);
        break;
    case '4':
        setRenWu($_POST['opurlType'],$_POST['planId'],$_POST['opType']);
        break;
    case '5':
        getAI($_POST['url'],$_POST['data']);
        break;
    case '6':
        createRenWu_WeiJie($_POST['planId'],$_POST['data']);
        break;
    case '7':
        echo dangRiSubmitCount();  //当日提交客资数量
        break;
    case '8':
        echo aiCall();  //当日提交客资数量
        break;

    default:
        # code...
        break;
}

   //echo $_POST['data'].'<br>'.$_POST['url'].'<br>';

    //getAI($_POST['url'],$_POST['data']);

//getAI('/thirdApi/bss/queryPlanCallList','{"pageNo":"1","pageSize":"20"}');  //查询任务 

/*****返回list数组中 需要获取参数 list[id] list[planName] 任务名称  list[status]任务状态  list[planNum]任务数电话号码数********/

//getAI('/thirdApi/bss/queryPlanPhonePage','{"planId":"32520","pageNo":"1","pageSize":"3000"}');  //查询 通过任务id 查询电话号码通话

    /*******

    返回list数据中 需要获取的参数 
    list[callId] 通话ID list[reason]意向备注  
    list[result]意向标签 list[billSec]接听时长 
    list[recallNum ]通话轮数 list[isRead]是否已读  
    list[alreadyNum] 已拨次数  
    list[fReason] 通话状态【-2、拨打次 数达限 -1、外呼失 败 0、已接听 1、主叫停机 2、被叫停机 3、关机或不 在服务区 4、占线 5、空号 6、呼叫受限 7、用户挂断 8、无效号码 10、无人接 听 -99、其它 9、呼损 99、识别中 】  

    ************/

// '{"callId":"1273866301412626432"}'
//getAI('/thirdApi/bss/findCallDetailById',$_POST['data']);

    /**返回body数据中 需要获取的参数
        body[file_all] 音频总文件 url

        body[file_part] 音频分文件

    ***/




function getAI($urli,$json){  //1获取AI系统API

    $accessKey='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLZzlW68fR5x7vztskx9IvUNpsZpqfzK1QZTmQb-XH3Nn3LOGBlCMCJ_G3OQczfJnQumsqrz_vRI8c9gWhACLIwUHcHEntD3YekwxxdCR0S2EPZlwjk2t9DYHYUZQvBGHt0luclKGsP85hLCWgNMeJVKPCUPfZNwHTxBoThBwfIQIDAQAB';

    $nonce=createInvitecode();

    list($msec, $sec) = explode(' ', microtime());

    $timestamp = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);


    $secretKey='MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAItnOVbrx9HnHu_O2yTH0i9Q2mxmmp_MrVBlOZBv5cfc2fcs4YGUIwIn8bc5BzN8mdC6ayqvP-9Ejxz2BaEAIsjBQdwcSe0Pdh6TDHF0JHRLYQ9mXCOTa30NgdhRlC8EYe3SW5yUoaw_zmEsJaA0x4lUo8JQ99k3AdPEGhOEHB8hAgMBAAECgYEAidXmvCslyEXeMP83b4akLGSlk8lf2eFm_LcZ09bQPG4CloOp9ZWjh943AhNBK4doDxpEHFBrxwji-J_JsQeRW7TUZXEBZ3_JQJUO9pnB-kWNqBTcJYTrlCAwsLtJTo0KfAhj5lUupU_y-hmx6wB1mDsu-k2bsIkgSbBkzJxYxgECQQDb6RhW-Ag8ZUYFaVkNVX6Etm9nrH7k5wEURKXw1RENW15bbZnAEy2MbBTSVwvdO7b5kJhwyF7lRnVRCK7HRBqlAkEAokfY3I3YrvhRq4mDMRv_Ok8rbQiqPW5DCcfwVujL9Ods4J3t3zgsBxq0eHq-nrfYOzBIGoEm_VftvltcY7JVzQJAS2pNsY2P7X5hm_t70anPIJ4b6HbscX2TDitYqRW4qlb6LeqRPqCVD0IFhfjaFb2jy0Q-MvdUK9aU5vxOTAHcDQJAG0APVXHoSfFe3Xw48H0wDZ2PwD5tP-WNEk5luGJdJWHbMZizggFPu12ronOSINrkT4QbB4BaiL5EKOv0hrVCnQJAFkBEdSqxe11Jc-HTsEq77VzK7pz3PD6Q9xt2PsvQ5daVm3kfSdWzrfcUciqLyN9FvZPFojRX2FEOkAOLpZosyw';

    $md5=md5('accessKey='.$accessKey.'&nonce='.$nonce.'&timestamp='.$timestamp.$secretKey);

    $data= ['timestamp'=>$timestamp,'accessKey'=>$accessKey,'signType'=>'MD5','nonce'=>$nonce,'sign'=>$md5];

    //$dataPost=["pageNo"=>1,"pageSize"=> 10];

    $dataPost=json_decode($json,true);

    //var_dump($dataPost);

    $dataA=array_merge($data,$dataPost);

    //var_dump(array_merge($data,$dataPost));


    $url='https://bss.guiji.ai:18089'.$urli;

    posturl($url,$dataA,$md5,$timestamp);


}


function  setJsonTell($file,$callId){  //2将以读的callid放到json中记录


        $json_string = file_get_contents($file); 

        $arr=json_decode($json_string,true);

        $arrCallId=array('callId'=>$callId);

       // $arr=array('data'=>[['callId'=>$callId]]);

        $arr1=array_unique($arr['data']);  //数组去重

        $y=0;

        for($i=0;$i<count($arr['data']);$i++){

            $yuanL=$arr['data'][$i]['callId'];

            if($yuanL==$callId){

                //var_dump($arr['data'][$i]['callId']);

                array_splice($arr['data'],$i,1);

                $y++;
            }
        }

        array_push($arr['data'], $arrCallId);

        // echo $y;

        // var_dump($arr);

        $json = json_encode($arr,JSON_UNESCAPED_UNICODE);

        $ar=array('data'=>file_put_contents($file, $json));

        $jsonEcho=json_encode($ar,JSON_UNESCAPED_UNICODE);
  
        echo $jsonEcho;


        //$arr1=array(['callId'=>$callId]);


        $qure="UPDATE GJ_datapnone SET isRead=1 WHERE callId='{$callId}';";
        $qure1="UPDATE by_data SET isRead=1 WHERE callInstanceId='{$callId}';";

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';

        $link=mysqli_connect($host, $user, $password, $database);
        $link1=mysqli_connect($host, $user, $password, $database);

        $link->query("set names utf8");
        $link1->query("set names utf8");

        $result=mysqli_query($link, $qure);
        $result1=mysqli_query($link1, $qure1);

        return "[{'result':'{$result}'},{'result':'{$result1}'}]";


}

function createRenWu_tell($planId,$starTime,$endTime){  //3



    $tell=json_decode(selectTellDB($starTime,$endTime),true);

    $arr=[];

    for($i=0;$i<count($tell['data']);$i++){

        $name=$tell['data'][$i]['shengFen'].'|'.$tell['data'][$i]['city'].'客户|'.($i+1);

        $phone=$tell['data'][$i]['tell'];

        //var_dump($tell['data'][$i]['shengFen'].'|'.$tell['data'][$i]['city'].'客户|'.($i+1));

        $arr[$i]=['phone'=>$phone,'custName'=>$name];

    }

    $ar=array('planId'=>$planId,'phoneList'=>$arr);

    $json=json_encode($ar,JSON_UNESCAPED_UNICODE);

    getAI('/thirdApi/bss/callImportPhone',$json);

    //导入电话
    // mydict1=getAI('/thirdApi/bss/callImportPhone',{'planId':'35166','phoneList':[{'phone':'18801263882','custName':'北京|北京客户|1'},{'phone':'18801263883','custName':'北京|北京客户|1'}]});
    // print(mydict1)

}




function setRenWu($opurlType,$planId,$opType){  //4用来进行任务 停止/导入/暂停/开始 的函数


     $ar=array('planId'=>$planId,'opType'=>$opType);

     $json=json_encode($ar,JSON_UNESCAPED_UNICODE);
    
     getAI('/thirdApi/bss/'.$opurlType,$json);
}


function createRenWu_WeiJie($planId,$data){  //6 把未接电话放到新建任务里面



    $tell=json_decode($data,true);

    $arr=[];

    for($i=0;$i<count($tell);$i++){

        $name=$tell[$i]['custName'];

        $phone=$tell[$i]['phone'];

        //var_dump($tell['data'][$i]['shengFen'].'|'.$tell['data'][$i]['city'].'客户|'.($i+1));

        $arr[$i]=['phone'=>$phone,'custName'=>$name];

    }

    $ar=array('planId'=>$planId,'phoneList'=>$arr);

    $json=json_encode($ar,JSON_UNESCAPED_UNICODE);

    getAI('/thirdApi/bss/callImportPhone',$json);

    //导入电话
    // mydict1=getAI('/thirdApi/bss/callImportPhone',{'planId':'35166','phoneList':[{'phone':'18801263882','custName':'北京|北京客户|1'},{'phone':'18801263883','custName':'北京|北京客户|1'}]});
    // print(mydict1)

}

function dangRiSubmitCount(){ //7

    $qure="SELECT COUNT(*) as count FROM everydaytell WHERE submit BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59';";
    $host='localhost';
    $user='root';
    $password='root';
    $database='weizandata';
    $link=mysqli_connect($host, $user, $password, $database);
    $link->query("set names utf8");
    $result=mysqli_query($link, $qure);
    $arr=mysqli_fetch_all($result, 1);
    $jsonData=json_encode($arr);
    $json = json_encode(array(
            "code"=>0,
            "msg"=>$qure,
            "count"=>count($arr),
            "data"=>$arr[0]['count'] ),
            JSON_UNESCAPED_UNICODE);
    
    mysqli_close($link);

    return $json;

} 


function selectTellDB($starTime,$endTime){  //34


    $qure="SELECT * FROM  everyDayTell WHERE riqi BETWEEN '{$starTime}' AND '{$endTime}';";
    $host='localhost';
    $user='root';
    $password='root';
    $database='weizandata';
    $link=mysqli_connect($host, $user, $password, $database);
    $link->query("set names utf8");
    $result=mysqli_query($link, $qure);
    $arr=mysqli_fetch_all($result, 1);
    $jsonData=json_encode($arr);
    $json = json_encode(array(
            "code"=>0,
            "msg"=>"",
            "count"=>count($arr),
            "data"=>$arr ),
            JSON_UNESCAPED_UNICODE);
    
    mysqli_close($link);

    return $json;

}

function aiCall(){  

    $offset=$_POST['limit']*($_POST['page']-1);
    $qure="call aiCall({$_POST['limit']},{$offset});";
    $qureCount="call aiCallCount()";
    $host='localhost';
    $user='root';
    $password='root';
    $database='weizandata';
    $link=mysqli_connect($host, $user, $password, $database);
    $link1=mysqli_connect($host, $user, $password, $database);
    $link->query("set names utf8");
    $link1->query("set names utf8");
    $result=mysqli_query($link, $qure);
    $resultCount=mysqli_query($link1,$qureCount);
    $arr=mysqli_fetch_all($result, 1);
    $arrCount=mysqli_fetch_all($resultCount, 1);
    
    $jsonData=json_encode($arr);
    $json = json_encode(array(
            "code"=>0,
            "msg"=>"",
            "count"=>$arrCount[0]['count'],
            "data"=>$arr ),
            JSON_UNESCAPED_UNICODE);
    
    mysqli_close($link);

    return $json;

}
function posturl($url,$data){

        $data  = json_encode($data);
        $headerArray = array("Content-Type: application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $put = curl_exec($curl);
        echo $put;
        curl_close($curl);
       // return json_decode($put，true);
}

function createInvitecode(){

    // 生成字母和数字组成的6位字符串

   $str = range('A', 'Z');

    // 去除大写的O，以防止与0混淆 

   unset($str[array_search('O', $str)]);

    $arr = array_merge(range(0, 9), $str);

     shuffle($arr);

    $invitecode = '';

    $arr_len = count($arr);

    for ($i = 0; $i < 6; $i++) {

        $rand = mt_rand(0, $arr_len - 1);

        $invitecode .= $arr[$rand];

    }

    return $invitecode ;

}

?>



